package io.gitee.mayan50.autoassociate.util;

import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 数据库工具类 实现自定义sql
 */
public class DBUtils {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    public <E> E executeQuerySqlOne(String sql, Class<E> classType) {
        return executeQuerySqlOne(sql, classType, null);
    }

    public <E> E executeQuerySqlOne(String sql, Class<E> classType, String[] condition) {
        List<E> list = executeQuerySql(sql, classType, condition);
        if (list == null || list.isEmpty()) return null;
        if (list.size() > 1) throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records");
        return list.get(0);
    }

    public <E> List<E> executeQuerySql(String sql, Class<E> classType) {
        return executeQuerySql(sql, classType, null);
    }

    public <E> List<E> executeQuerySql(String sql, Class<E> classType, String[] condition){
        List<E> list = new ArrayList<>();
        PreparedStatement pst = null;
        SqlSession session = getSqlSession();
        ResultSet result = null;
        try {
            pst = session.getConnection().prepareStatement(sql);
            if (condition != null) for (int i = 1; i <= condition.length; ++i) pst.setString(i, condition[i - 1]);
            result = pst.executeQuery();
            ResultSetMetaData md = result.getMetaData(); //获得结果集结构信息,元数据
            while (result.next()) {
                E e = classType.newInstance();
                for (int i = 1; i <= md.getColumnCount(); ++i) {
                    Field field = classType.getDeclaredField(StrUtils.humpToLine(md.getColumnName(i)));
                    field.setAccessible(true);
                    field.set(e, result.getObject(i));
                }
                list.add(e);
            }
        } catch (SQLException | InstantiationException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }finally {
            if(pst != null){
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            closeSqlSession(session);
        }
        return list;
    }

    /**
     * 获取sqlSession
     * @return SqlSession
     */
    public SqlSession getSqlSession(){
        return SqlSessionUtils.getSqlSession(sqlSessionTemplate.getSqlSessionFactory(),
                sqlSessionTemplate.getExecutorType(), sqlSessionTemplate.getPersistenceExceptionTranslator());
    }

    /**
     * 关闭sqlSession
     */
    private void closeSqlSession(SqlSession session){
        SqlSessionUtils.closeSqlSession(session, sqlSessionTemplate.getSqlSessionFactory());
    }

}
